import { h } from 'vue';

export default {
  name: 'ellipsis',
  props: {
    title: { default: undefined },
    tooltip: { type: Boolean, default: true },
    ellipsis: { type: Boolean, default: true },
    maxWidth: { type: String, default: undefined },
    maxLength: { type: Number, default: undefined },
  },
  computed: {
    ellipsisStyle() {
      return Object.assign(
        {
          maxWidth: this.maxWidth ? this.maxWidth : '100%',
          display: 'inline-block',
          lineHeight: '100%',
        },
        this.ellipsis === false ? {} : { overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }
      );
    },
  },
  methods: {
    getSlotText(slot) {
      if (typeof slot.children === 'string') {
        return slot.children;
      }
      if (Array.isArray(slot.children)) {
        return slot.children.map((item) => this.getSlotText(item)).join('');
      }
      return '';
    },
    getTitle() {
      if (this.title !== undefined) {
        return this.title;
      }
      if (this.$slots.default) {
        const text = this.$slots.default();
        return text.map(this.getSlotText).join('');
      }
    },
  },
  render() {
    const title = this.title !== undefined ? String(this.title) : '';
    return h(
      this.tooltip ? 'a-tooltip' : 'span',
      {
        title: this.getTitle(),
        style: this.ellipsisStyle,
      },
      this.$slots.default
        ? this.$slots.default()
        : this.maxLength > 0 && title.length > this.maxLength
        ? title.substring(0, this.maxLength)
        : title
    );
  },
};
